import router, { resetRouter } from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

/**
 * 基本逻辑：
 * 1、判断是否存在Token，不存在导航至Login
 * 2、判断是否存在权限信息Roles，不存在则重新请求权限接口，重新匹配路由，挂载
 * 3、权限信息不存本地，否则极易存在安全风险
 */
const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = store.getters.token
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          let roles = await store.dispatch('user/getRoles')
          const accessRoutes = await store.dispatch(
            'permission/generateRoutes',
            roles
          )
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          await store.dispatch('user/logout')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    // 不存则导航登录页
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      resetRouter()
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
